package com.vtech.ws.cxf.client;


import com.vtech.ws.cxf.HiService;
import com.vtech.ws.cxf.service.FileEntity;
import com.vtech.ws.cxf.service.SoapFileService;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.stereotype.Component;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import java.io.File;

/**
 * TODO
 * 首先使用wsdl2java插件生成客户端的代码
 *
 * @author houzhiwei
 * @date 2018 /9/9 10:42
 */
@Component
public class SoapClient {

    /**
     * Main.
     *
     * @param args the args
     */
    public static void main(String args[]) {
        //proxyClient();
        springClient();
    }

    /**
     * Proxy client.
     * CXF静态代理客户端
     * 客户端也必须依赖服务器端的接口，这种调用方式限制是很大的，要求服务器端的webservice必须是java实现?
     */
    public static void proxyClient() {
        JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
        factory.setServiceClass(SoapFileService.class);
        //factory.setAddress(clientConfig.getFileServiceAddress()); // 直接运行时不能读取配置文件内容
        factory.setAddress("http://localhost:8008/ws/services/FileService");
        //TODO add Interceptors
        FileEntity uploadFile = new FileEntity();
        uploadFile.setExtension("tif");
        uploadFile.setName("xcDEM");
        DataSource source = new FileDataSource(new File("H:/xcDEM.tif"));
        uploadFile.setFile(new DataHandler(source));

        SoapFileService client = (SoapFileService) factory.create();
        String resp = client.upload(uploadFile);
        System.out.println(resp); //SUCCESS
    }


    /**
     * spring  Client with xml configuration.
     * http://cxf.apache.org/docs/jax-ws-configuration.html
     */
    public static void springClient(){
        ApplicationContext context = new ClassPathXmlApplicationContext("cxf-client.xml");
        HiService helloService = context.getBean("HiService", HiService.class);
        String result = helloService.sayHi("world");
        System.out.println(result);
    }

}
